package com.insight.modules.message.websocket;

import com.alibaba.fastjson.JSONObject;
import com.insight.common.api.vo.Result;
import com.insight.common.message.webssh.pojo.WebsocketConst;
import com.insight.common.mq.RedisMq;
import com.insight.common.mq.stream.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sys/socketTest")
public class TestSocketController {

	@Autowired
	private RedisMq redisMq;

	/**
	 * 群发消息接口
	 * @param jsonObject 请求体，包含消息内容
	 * @return 发送结果
	 */
	@PostMapping("/sendAll")
	public Result<String> sendAll(@RequestBody JSONObject jsonObject) {
		Result<String> result = new Result<>();
		// 从请求中获取消息内容
		String message = jsonObject.getString("message");

		// 构造WebSocket消息对象，指定为群发命令和消息ID
		JSONObject obj = new JSONObject();
		obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC);
		obj.put(WebsocketConst.MSG_ID, "M0001");
		obj.put(WebsocketConst.MSG_TXT, message);

		// 通过Redis发布消息，推送到所有订阅的客户端
		redisMq.publish(Streams.WEBSOCKET_PUBLICIZE, jsonObject);

		result.setResult("群发！");
		return result;
	}

	/**
	 * 单独发送消息给指定用户接口
	 * @param jsonObject 请求体，包含用户ID和消息内容
	 * @return 发送结果
	 */
	@PostMapping("/sendUser")
	public Result<String> sendUser(@RequestBody JSONObject jsonObject) {
		Result<String> result = new Result<>();
		// 从请求中获取目标用户ID和消息内容
		String userId = jsonObject.getString("userId");
		String message = jsonObject.getString("message");

		// 构造WebSocket消息对象，指定为单用户命令、用户ID和消息内容
		JSONObject obj = new JSONObject();
		obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
		obj.put(WebsocketConst.MSG_USER_ID, userId);
		obj.put(WebsocketConst.MSG_ID, "M0001");
		obj.put(WebsocketConst.MSG_TXT, message);

		// 通过Redis发布消息，推送给指定用户
		redisMq.publish(Streams.WEBSOCKET_PUBLICIZE, jsonObject);

		result.setResult("单发");
		return result;
	}

}

